package com.ywdnf.gomoku.web.socket;

import com.ywdnf.gomoku.ai.AIPlayer;
import com.ywdnf.gomoku.model.chess.ChessState;
import com.ywdnf.gomoku.model.chess.Chessman;
import com.ywdnf.gomoku.model.chess.Point;
import com.ywdnf.gomoku.model.chess.Game;
import com.ywdnf.gomoku.model.chess.GameState;
import com.ywdnf.gomoku.model.chess.Player;
import com.ywdnf.gomoku.model.chess.Round;
import com.ywdnf.gomoku.model.message.GmkRequest;
import com.ywdnf.gomoku.util.CommonUtil;
import com.ywdnf.gomoku.util.Const;
import com.ywdnf.gomoku.util.GmkMsgUtils;
import com.ywdnf.gomoku.util.MessageUtils;
import com.ywdnf.gomoku.web.control.GomokuController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 五子棋对战终端
 *
 * @author lss
 * @date 2019-06-26, Wed
 */
@Controller
public class GomokuServer {

  @Autowired
  private SimpMessagingTemplate simpMessagingTemplate;


  @MessageMapping("/gmk/opt/{gameId}/{userId}")
  public void gmkChanged(
      @DestinationVariable(Const.PARAM_GAME_ID_IN_URL) String gameId,
      @DestinationVariable(Const.PARAM_USER_ID_IN_URL) String userId,
      @RequestBody GmkRequest req) {
    switch (req.getRequestNo()) {
      case GmkRequest.REQUEST_PLACE_CHESS:
        Game game = GomokuController.getGame(gameId);
        if (game.getState() != GameState.RUNNING) {
          return;
        }
        Round round = game.getCurrentRound();

        boolean b = round.getCurLayout()
            .modChessman(new Point(req.getX(), req.getY()), ChessState.PLACED, round.getCurOptPlayer(),true);
        System.out.println(round.getCurOptPlayer().getClass());
        if (b) {
          // 当前用户步数增加
          round.addOptPlayerStep();
          // 通知落子的用户落子成功
          GmkMsgUtils.sendPlaceChessResultMsg(round.getCurOptPlayer());
          // 修改两个用户的棋子
          GmkMsgUtils
              .sendModChessMsg(game, new Chessman(new Point(req.getX(), req.getY()), round.getCurOptPlayer()));
          // 检查是否有玩家获得胜利
          if (round.getCurLayout().isFinish()) {
            round.setFinish(true);
            // 当前玩家获胜
            round.setWinner(round.getCurLayout().getP());
            // 增加用户积分
            GmkMsgUtils.sendRoundResultMsg(game, round);
            game.setState(GameState.PAUSE);
            return;
          } else {
            // 重置当前操作的玩家
            Player othPlayer = CommonUtil.getOthPlayer(userId, game);
            assert othPlayer != null;
            if (game.isAiGame()) {
              AIPlayer aiPlayer = (AIPlayer) othPlayer;
              // 自动下棋
              aiPlayer.autoPlace();
              if (round.getCurLayout().isFinish()) {
                round.setFinish(true);
                // 当前玩家获胜
                round.setWinner(aiPlayer);
                // 增加用户积分
                GmkMsgUtils.sendRoundResultMsg(game, round);
                game.setState(GameState.PAUSE);
                return;
              }
              //
              round.setCurOptPlayer(CommonUtil.getOthPlayer(aiPlayer.getUserId(), gameId));
              // 玩家继续落子
              round.setCurOptPlayer(round.getCurOptPlayer());
              GmkMsgUtils.sendPlaceChessMsg(round.getCurOptPlayer());
            } else {
              round.setCurOptPlayer(othPlayer);
              GmkMsgUtils.sendPlaceChessMsg(othPlayer);
            }
          }

        } else {
          // 未知错误
          MessageUtils.sendToGameUserSameMsg(game, null);
        }

        break;
      case GmkRequest.REQUEST_SEND_MESSAGE:
        String msgBody = req.getBody();
        if (msgBody.trim().toUpperCase().startsWith(Const.BACK_DOOR_1)) {
          String[] split = msgBody.split("\\s+");
          Player player = CommonUtil.getSelfPlayer(userId, gameId);
          player.setIntegral(player.getIntegral() + Integer.parseInt(split[split.length - 1]));
        } else {
          GmkMsgUtils.sendPlayerMessage(gameId, userId, msgBody);
        }
        break;
      default:
        break;
    }
  }
}
